//
//  FlutterNativePWDAESPlugin.m
//  Runner
//
//  Created by mac on 2020/3/15.
//  Copyright © 2020 The Chromium Authors. All rights reserved.
//

#import "FlutterNativePWDAESPlugin.h"
#import "JKEncrypt.h"

@interface FlutterNativePWDAESPlugin()

@property (nonatomic, strong) UIViewController *controller;
@end

@implementation FlutterNativePWDAESPlugin

static NSString *const CHANNELNAME = @"xinAnLi";
static NSString *const METHODNAME  = @"passwordAes";

/**
 *plugin 注册
 */
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:CHANNELNAME binaryMessenger:[registrar messenger]];
    
    UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;

    FlutterNativePWDAESPlugin *plugin = [[FlutterNativePWDAESPlugin alloc]initWithViewController:viewController];
    
    [registrar addMethodCallDelegate:plugin channel:channel];
}

/**
 *flutter端通过通道调用原生方法时会进入以下回调
 */
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    
   //call的属性method是flutter调用原生方法的方法名，我们进行字符串判断然后写入不同的逻辑
            NSString *methodName = call.method;
            if ([methodName isEqualToString:METHODNAME]) {
                //flutter传给原生的参数
                id para = call.arguments;
    //            NSLog(@"flutter传给原生的参数：%@", para);
                //获取一个字符串
                NSString *nativeFinalStr = [JKEncrypt doEncryptStr:para];
                if (nativeFinalStr != nil) {
                    //把获取到的字符串传值给flutter
    //                NSLog(@"传给flutter的参数:%@",nativeFinalStr);
                    result(nativeFinalStr);
                }else{
                    //异常(比如改方法是调用原生的getString获取一个字符串，但是返回的是nil(空值)，这显然是不对的，就可以向flutter抛出异常 进入catch处理)
                    result([FlutterError errorWithCode:@"001" message:[NSString stringWithFormat:@"进入异常处理"] details:@"进入flutter的trycatch方法的catch方法"]);
                }
            }else{
                //调用的方法原生没有对应的处理  抛出未实现的异常
                result(FlutterMethodNotImplemented);
            }
}
- (instancetype)initWithViewController:(UIViewController *)viewController {
    self = [super init];
    if (self) {
        self.controller = viewController;
    }
    return self;
}
@end
